package com.kb.erp.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kb.erp.domain.CrmCustomerDept;
import com.kb.erp.entity.CRMSalesOrder;
import com.kb.erp.entity.HrEntity;
import com.kb.erp.entity.crm.Customer;
import com.kb.erp.entity.crm.CustomerAddress;
import com.kb.erp.entity.crm.XnhUserInfo;
import com.kb.erp.mapper.sqlServer.crm.CRMCustomerMapper;
import com.kb.erp.mapper.sqlServer.crm.CRMSalesOrderMapper;
import com.kb.erp.mapper.sqlServer.crm.CRMUserInfoMapper;
import com.kb.erp.mapper.sqlServer.crm.CustomerAddressMapper;
import com.kb.erp.service.CrmService;
import com.kb.erp.service.HrService;
import com.kb.erp.util.MessageUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
@DS("SmartQuote_kb_live")
public class CrmServiceImpl implements CrmService {

    @Resource
    private CRMSalesOrderMapper crmSalesOrderMapper;
    @Resource
    private CRMCustomerMapper customerMapper;
    @Resource
    private CRMUserInfoMapper crmUserInfoMapper;
    @Resource
    private CustomerAddressMapper customerAddressMapper;
    @Resource
    private HrService hrService;

    @Override
    public List<CRMSalesOrder> querySalesOrder(String code) {
        LambdaQueryWrapper<CRMSalesOrder> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CRMSalesOrder::getSalesOrder, code);
        return crmSalesOrderMapper.selectList(queryWrapper);
    }

    @Override
    public int del(String code) {
        LambdaQueryWrapper<CRMSalesOrder> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CRMSalesOrder::getSalesOrder, code);
        return crmSalesOrderMapper.delete(queryWrapper);
    }

    @Override
    public List<Customer> queryCustomerByCode(String code) {
        LambdaQueryWrapper<Customer> queryWrapper = Wrappers.lambdaQuery();
        if (Objects.nonNull(code)) {
            queryWrapper.eq(Customer::getCustcode, code);
        }
        //todo 日常数据更新加上时间筛选
        List<Customer> customers = customerMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(customers)) {
            return null;
        }
        return customers;
    }

    @Override
    public List<CustomerAddress> queryCustAddress(Integer id) {
        LambdaQueryWrapper<CustomerAddress> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CustomerAddress::getCustomerid, id);
        return customerAddressMapper.selectList(queryWrapper);
    }

    @Override
    public void updateUserCode() {
        //查询EmpNo为空，且IfActive为1的数据
        LambdaQueryWrapper<XnhUserInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.isNull(XnhUserInfo::getEmpNo);
        queryWrapper.eq(XnhUserInfo::getIfActive, 1);
        List<XnhUserInfo> userInfoList = crmUserInfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(userInfoList)) {
            //
            for (XnhUserInfo xnhUserInfo : userInfoList) {
                List<HrEntity> hrEntityList = new ArrayList<>();
                //判断xnhUserInfo.getUserid()是否是数字，如果是就要这个查询，查询不到就用用户名查询
                if (xnhUserInfo.getUserid().matches("\\d+")) {
                    hrEntityList = hrService.queryByParams(xnhUserInfo.getUserid());
                    if (CollectionUtils.isEmpty(hrEntityList)) {
                        hrEntityList = hrService.queryByParams(xnhUserInfo.getUsername());
                    }
                } else {
                    hrEntityList = hrService.queryByParams(xnhUserInfo.getUsername());
                }
                if (CollectionUtils.isNotEmpty(hrEntityList)) {
                    if (Objects.nonNull(hrEntityList.get(0).getEmpNo())) {
                        xnhUserInfo.setEmpNo(hrEntityList.get(0).getEmpNo());
                        crmUserInfoMapper.updateById(xnhUserInfo);
                    }
                } else {
                    MessageUtil.sentMessage("23988,25681", "未找到用户：" + xnhUserInfo.getUsername(), "更新crm用户工号");
                }
            }
        }
    }


    @Override
    public void updateCustomerDept(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            // 创建ExcelReader对象
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            // 读取所有行数据
            List<Map<String, Object>> rowList = reader.readAll();
            // 遍历每一行数据
            for (Map<String, Object> row : rowList) {
                // 获取业务员代码和部门编码
                String ywyCode = (String) row.get("业务员代码");
                String bmCode = (String) row.get("部门编码");
                System.out.println("业务员代码: " + ywyCode + ", 部门编码: " + bmCode);
            }
            // 关闭reader
            reader.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Page<CrmCustomerDept> queryCrmCustomerDept(CrmCustomerDept customerDept) {
        if (Objects.nonNull(customerDept.getSalesman())){
            customerDept.setSalesmanList(Arrays.asList(customerDept.getSalesman().split(",")));
        }
        Page<CrmCustomerDept> page = new Page<>(customerDept.getPageNo(), customerDept.getPageSize());
        return customerMapper.queryCrmCustomerDept(page,customerDept);
    }

    @Override
    public void updateCustomerDept(CrmCustomerDept customerDept) {
        if (Objects.nonNull(customerDept.getSalesman()) && Objects.nonNull(customerDept.getDept())){
            String salesman = customerDept.getSalesman();
            String[] list = salesman.split(",");
            for (String s : list) {
                customerMapper.updateCustomerDept(s,customerDept.getDept());
            }
        }
    }


}
